import { _decorator, JsonAsset, Node } from 'cc';
import { ResourceUtil } from '../Utils/ResourceUtil';

export class DataManager {
    static LocalGameData: GameData[] = [];
    static RemoteGameData: GameData[] = [];
    static AllGameData: GameData[] = [];

    public static async LoadData() {
        try {
            const ja = await ResourceUtil.LoadJson("GameData") as JsonAsset;
            const data = ja.json as any;

            let localGameNames = [];
            let remoteGameNames = [];

            for (let i = 0; i < data.LoaclGameData.length; i++) {
                localGameNames.push(data.LoaclGameData[i]);
            }

            for (let i = 0; i < data.RemoteGameData.length; i++) {
                remoteGameNames.push(data.RemoteGameData[i]);
            }

            for (let i = 0; i < data.AllGameData.length; i++) {
                let e = data.AllGameData[i];
                DataManager.AllGameData.push(new GameData(e.gameName, e.startScene, e.bundles));
            }

            //筛选出符合条件的数据
            for (let i = 0; i < localGameNames.length; i++) {
                const data = this.AllGameData.find(e => e.gameName == localGameNames[i]);
                this.LocalGameData.push(data);
            }

            for (let i = 0; i < remoteGameNames.length; i++) {
                const data = this.AllGameData.find(e => e.gameName == remoteGameNames[i]);
                this.RemoteGameData.push(data);
            }

            let str = "";
            this.LocalGameData.forEach(e => str += `[${e.gameName}] `);
            console.log(`本地游戏：${str}`);
            str = ""
            this.RemoteGameData.forEach(e => str += `[${e.gameName}] `);
            console.log(`远程游戏：${str}`);
        } catch (error) {
            console.error("Error loading game data:", error);
            return [];
        }
    }

    //**加载需要的资源 */
    public static async GetBundles(): Promise<string[]> {
        await DataManager.LoadData();

        let bundles: string[] = [];

        //添加本地分包
        this.LocalGameData.forEach(e => e.Bundles.forEach(e => { if (e) bundles.push(e) }));

        let str = ""
        bundles.forEach(e => str += `[${e}] `);
        console.log(`需要加载的本地包：${str}`);

        return bundles;
    }

    public static GetStartGameData() {
        return this.LocalGameData[0];
    }
}

export class GameData {
    constructor(public gameName: string, public startScene: string, private bundles: string) {
    }

    get Bundles() {
        return this.bundles.split(`,`).map(str => str.trim());
    }

    get DefaultBundle() {
        return this.Bundles[0];
    }
}

